import React, { Component } from 'react'
import {
  Upload,
  Modal,
  message,
  Icon,
  Button
} from 'antd';
import File from './File'
import Image from './Image'
class UploadFile extends Component {
  state = {
    previewVisible: false,
    previewImage: {},
    previewType: '',
    fileUploading: false,
    fileList: [],
    width: 0
  }
  componentDidMount() {
    // 获取文件列表
    const { value } = this.props
    // 获取设置的宽度
    const { width } = this.props
    // 如果没有设置宽度,就获取元素的宽度
    let currentWidth = width ? width : this.refs.file.clientWidth
    this.setState({ width: currentWidth })
    this.getValue(value)
  }
  componentWillReceiveProps({ value }) {
    this.getValue(value)
  }
  getValue = (value) => {
    if (value && value.length) {
      this.setState({ fileList: value })
    }
  }
  beforeUpload = file => {
    // 获取设置的可以上传的文件类型
    const { uploadInfo: { accept } } = this.props;
    // 将文件名按‘.’分割,倒序,然后取出首个,即为文件名,然后转小写
    let fileName = file.name.split('.').reverse()[0].toLowerCase()
    // 判断当前上传的文件是否为允许的格式
    if (!accept.includes(fileName)) {
      message.error('文件格式不正确', 10);
      return false;
    }
    // 判断是否是图片类型
    const imgType = ['jpg', 'jpeg', 'png']
    const isImg = imgType.includes(fileName)
    // 图片类型大小为2M 非图片类型为10M
    let maxSize = isImg ? 2 : 10
    const scaleOut = file.size / 1024 / 1024 <= maxSize
    if (!scaleOut) {
      message.error(`上传文件必须小于${maxSize}MB!`, 10);
      return false
    }
    return true;
  }

  handleCancel = () => this.setState({ previewVisible: false })

  handlePreview = (item) => {
    const fileName = item.name.split('.').reverse()[0].toLowerCase()
    const imgType = ['jpg', 'jpeg', 'png', 'pdf']
    const canPreview = imgType.includes(fileName)
    if (!canPreview) return message.error(`暂不支持预览${fileName}格式的文件`, 10)
    this.setState({
      previewImage: item,
      previewVisible: true,
      previewType: fileName
    });
  }

  handleChange = info => {
    const { onChange } = this.props
    const { fileList } = this.state
    if ('uploading' === info.file.status) {
      this.setState({ fileUploading: true })
      return
    }
    if ('done' === info.file.status) {
      if (info.file.response.errorCode === 0) {
        this.setState({ fileUploading: false, fileList: [...fileList, info.file.response.data] })
        onChange([...fileList, info.file.response.data])
      } else {
        this.setState({ fileUploading: false })
        message.error(info.file.response.msg, 10)
      }
    }
  }

  handleRemoveFile = file => {
    const { onChange } = this.props
    const { fileList } = this.state
    this.setState({ fileList: fileList.filter(item => item.id !== file.id) })
    onChange(fileList.filter(item => item.id !== file.id))
  }

  render() {
    const { uploadInfo, isView = false, type = 'card', marginLeft = 0, max = 9999, placeholder = '' } = this.props
    const { previewVisible, previewImage, fileUploading, fileList, width, previewType } = this.state
    return (
      <div style={{ width, marginLeft, maxHeight: '222px', overflowY: 'auto' }} ref='file'>
        {
          type === 'card' && fileList.map(item => (<Image isUploading={!isView} key={item.id} item={item} handlePreview={this.handlePreview} handleRemove={this.handleRemoveFile} />))
        }
        <Upload
          {...uploadInfo}
          showUploadList={false}
          beforeUpload={this.beforeUpload}
          onChange={this.handleChange}
        >
          {(!isView && !((max - fileList.length) === 0)) && (
            type === 'card' ?
              <div>
                <Icon type={fileUploading ? 'loading' : 'plus'} />
                {placeholder && <div className="ant-upload-text">{placeholder}</div>}
              </div>
              :
              <Button>
                <Icon type={fileUploading ? 'loading' : 'paper-clip'} /> {placeholder}
              </Button>
          )
          }
        </Upload>
        {
          type === 'list' && fileList.map(item => (<File width={width} isUploading={!isView} key={item.id} item={item} handlePreview={this.handlePreview} handleRemove={this.handleRemoveFile} />))
        }
        <Modal maskClosable={false}
          keyboard={false}
          visible={previewVisible}
          footer={null}
          onCancel={this.handleCancel}
          width={800}
          bodyStyle={{ padding: '40px' }}
          title={previewImage.name}
        >
          {
            previewType !== 'pdf' &&
            <img alt={previewImage.name} style={{ width: '100%' }} src={(previewImage.path || '').replace('_150x150', '')} />
          }
          {
            previewType === 'pdf' &&
            <iframe style={{ width: '100%', height: '800px' }} src={previewImage.path} title={previewImage.name} frameborder="0"></iframe>
          }
        </Modal>
      </div>
    )
  }
}

export default UploadFile
